package boot3.service.impl;

import boot3.mapper.NoticeMapper;
import boot3.mapper.NoticeUserMapper;
import boot3.mapper.UserMapper;
import boot3.pojo.NoticeUser;
import boot3.pojo.User;
import boot3.service.NoticeService;
import boot3.pojo.Notice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

@Service
public class NoticeServiceImpl implements NoticeService {

    @Autowired
    NoticeMapper noticeMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    NoticeUserMapper noticeUserMapper;
    @Override
    public List<Notice> findAllNotice(String chatroom_id) {
        return noticeMapper.findAllNotice(chatroom_id);
    }

    @Override
    public Boolean addNotice(Notice notice) {
        //先获取notice列表的长度
        List<Notice> allNotice = noticeMapper.findNotices();
        int length = allNotice.size()-1;
        String noticeId = allNotice.isEmpty()?"9999999":allNotice.get(length).getNotice_id();
        String notice_id = String.valueOf(Integer.parseInt(noticeId)+1);
        notice.setNotice_id(notice_id);
        notice.setPublish_time(getTime());
        //如果是1000号聊天室新添加的公告的话，那么就要更新user_notice列表
        if(notice.getChatroom_id().equals("1000")){
            //获取所有的老师和学生
            List<User> teas = userMapper.findByType("tea");
            for (User tea : teas) {
                NoticeUser noticeUser = new NoticeUser();
                noticeUser.setNotice_id(notice_id);
                noticeUser.setUser_id(tea.getUserID());
                noticeUser.setIs_read(false);
                noticeUserMapper.insertNotice(noticeUser);
            }
            List<User> stus = userMapper.findByType("stu");
            for (User stu : stus) {
                NoticeUser noticeUser1 = new NoticeUser();
                noticeUser1.setNotice_id(notice_id);
                noticeUser1.setUser_id(stu.getUserID());
                noticeUser1.setIs_read(false);
                noticeUserMapper.insertNotice(noticeUser1);}
        }
        return noticeMapper.addNotice(notice.getNotice_id(),notice.getNotice_content(),notice.getPublisher_id(),
                notice.getPublish_time(),notice.getChatroom_id());
    }

    @Override
    public Boolean deleteNotice(String notice_id) {
        return noticeMapper.deleteNotice(notice_id);
    }

    //获取当前的时间
    private String getTime(){
        Calendar calendar= Calendar.getInstance();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return dateFormat.format(calendar.getTime());
    }
}
